<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二手优选 - 安全可靠的二手交易平台</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#FF7D00',
                        neutral: {
                            100: '#F5F7FA',
                            200: '#E4E7ED',
                            300: '#C0C6CF',
                            400: '#909399',
                            500: '#606266',
                            600: '#303133',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 20px 0 rgba(0, 0, 0, 0.08)',
                        'card-hover': '0 8px 30px 0 rgba(0, 0, 0, 0.12)',
                        'modal': '0 10px 50px 0 rgba(0, 0, 0, 0.15)',
                    }
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .skeleton {
                background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
                background-size: 200% 100%;
                animation: skeleton-loading 1.5s infinite;
            }
            @keyframes skeleton-loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
            .coupon-selected {
                border: 2px solid #165DFF;
                background-color: rgba(22, 93, 255, 0.05);
            }
        }
    </style>

    <style>
        /* 全局样式 */
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            scroll-behavior: smooth;
        }

        /* 轮播图动画 */
        .carousel-item {
            transition: transform 0.5s ease-in-out;
        }

        /* 商品卡片悬停效果 */
        .product-card:hover {
            transform: translateY(-5px);
        }

        /* 优惠券领取动画 */
        @keyframes couponPulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        .coupon-hover:hover {
            animation: couponPulse 0.6s ease-in-out;
        }

        /* 领取成功动画 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .animate-fade-in {
            animation: fadeIn 0.5s ease-out forwards;
        }

        /* 无数据提示样式 */
        .empty-tip {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
            background-color: #f9fafb;
            border-radius: 0.75rem;
            color: #6b7280;
            font-size: 1rem;
        }

        /* 购买按钮样式 */
        .buy-btn {
            transition: all 0.3s ease;
        }
        .buy-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(22, 93, 255, 0.2);
        }
        .buy-btn:active {
            transform: translateY(0);
        }

        /* 优惠券选择弹窗样式 */
        .coupon-modal {
            backdrop-filter: blur(5px);
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }
        .coupon-modal-content {
            transform: translateY(20px);
            transition: transform 0.3s ease, opacity 0.3s ease;
        }
        .coupon-modal.active {
            opacity: 1;
            visibility: visible;
        }
        .coupon-modal.active .coupon-modal-content {
            transform: translateY(0);
            opacity: 1;
        }

        /* 优惠券选项样式 */
        .coupon-option {
            transition: all 0.2s ease;
        }
        .coupon-option:hover:not(.coupon-disabled) {
            background-color: rgba(22, 93, 255, 0.03);
        }
        .coupon-disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        .coupon-check {
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .coupon-selected .coupon-check {
            opacity: 1;
        }
    </style>
</head>

<body class="bg-neutral-100 text-neutral-600 font-inter">
<!-- 顶部通知栏 -->
<div class="bg-primary text-white text-center py-2 text-sm">
    <p>新用户注册立享10元优惠券 | 交易保障 · 安全无忧 <a href="#coupons" class="underline ml-2">领取优惠券</a></p>
</div>

<!-- 导航栏 -->
<header class="bg-white sticky top-0 z-50 shadow-sm transition-all duration-300" id="navbar">
    <div class="container mx-auto px-4 md:px-6">
        <div class="flex items-center justify-between h-16 md:h-20">
            <!-- Logo -->
            <a href="#" class="flex items-center space-x-2">
                <i class="fa fa-exchange text-primary text-2xl"></i>
                <span class="text-xl md:text-2xl font-bold text-primary">二手优选</span>
            </a>

            <!-- 主导航 - 桌面端（简化） -->
            <nav class="hidden md:flex items-center space-x-8">
                <a href="#" class="font-medium text-primary border-b-2 border-primary py-1">首页</a>
                <a href="#" class="font-medium text-neutral-500 hover:text-primary transition-custom py-1">全部商品</a>
                <a href="#" class="font-medium text-neutral-500 hover:text-primary transition-custom py-1">我要出售</a>
                <a href="#" class="font-medium text-neutral-500 hover:text-primary transition-custom py-1">帮助中心</a>
            </nav>

            <!-- 用户功能区 -->
            <div class="flex items-center space-x-4 md:space-x-6">
                <div class="relative hidden md:block">
                    <input type="text" placeholder="搜索商品、品牌..." class="w-64 pl-10 pr-4 py-2 rounded-full border border-neutral-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-custom">
                    <i class="fa fa-search absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400"></i>
                </div>

                <a href="#" class="relative text-neutral-500 hover:text-primary transition-custom" title="消息">
                    <i class="fa fa-bell-o text-xl"></i>
                    <span class="absolute -top-1 -right-1 bg-secondary text-white text-xs rounded-full h-4 w-4 flex items-center justify-center">3</span>
                </a>

                <a href="#" class="text-neutral-500 hover:text-primary transition-custom" title="购物车">
                    <i class="fa fa-shopping-cart text-xl"></i>
                </a>

                <a href="#" class="hidden md:flex items-center space-x-1 text-neutral-500 hover:text-primary transition-custom">
                    <i class="fa fa-user-o text-xl"></i>
                    <span>我的账户</span>
                </a>

                <!-- 移动端菜单按钮 -->
                <button class="md:hidden text-neutral-500 hover:text-primary transition-custom" id="menuToggle">
                    <i class="fa fa-bars text-2xl"></i>
                </button>
            </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-3">
            <div class="relative">
                <input type="text" placeholder="搜索商品、品牌..." class="w-full pl-10 pr-4 py-2 rounded-full border border-neutral-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary transition-custom">
                <i class="fa fa-search absolute left-4 top-1/2 -translate-y-1/2 text-neutral-400"></i>
            </div>
        </div>

        <!-- 移动端导航菜单（简化） -->
        <div class="md:hidden hidden bg-white border-t border-neutral-200" id="mobileMenu">
            <nav class="flex flex-col">
                <a href="#" class="px-4 py-3 text-primary font-medium border-l-4 border-primary">首页</a>
                <a href="#" class="px-4 py-3 text-neutral-500 hover:bg-neutral-50 transition-custom">全部商品</a>
                <a href="#" class="px-4 py-3 text-neutral-500 hover:bg-neutral-50 transition-custom">我要出售</a>
                <a href="#" class="px-4 py-3 text-neutral-500 hover:bg-neutral-50 transition-custom">帮助中心</a>
                <a href="#" class="px-4 py-3 text-neutral-500 hover:bg-neutral-50 transition-custom flex items-center space-x-2">
                    <i class="fa fa-user-o"></i>
                    <span>我的账户</span>
                </a>
            </nav>
        </div>
    </div>
</header>

<main>
    <!-- 轮播图区域 - 初始加载骨架屏 -->
    <section class="relative bg-white overflow-hidden">
        <div class="container mx-auto px-0">
            <div class="carousel relative h-[200px] md:h-[400px] lg:h-[500px] overflow-hidden" id="carousel">
                <!-- 轮播容器（动态填充） -->
                <div class="carousel-container flex h-full transition-transform duration-500" id="carouselContainer">
                    <!-- 加载中骨架屏 -->
                    <div class="carousel-item min-w-full h-full skeleton"></div>
                </div>

                <!-- 轮播控制按钮 -->
                <button class="absolute left-2 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white text-primary w-10 h-10 rounded-full flex items-center justify-center shadow-md transition-custom z-10" id="prevSlide">
                    <i class="fa fa-angle-left text-xl"></i>
                </button>
                <button class="absolute right-2 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white text-primary w-10 h-10 rounded-full flex items-center justify-center shadow-md transition-custom z-10" id="nextSlide">
                    <i class="fa fa-angle-right text-xl"></i>
                </button>

                <!-- 轮播指示器（动态填充） -->
                <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex space-x-2 z-10" id="carouselIndicators">
                    <!-- 指示器动态生成 -->
                </div>
            </div>
        </div>
    </section>

    <!-- 优惠券领取区 - 初始加载骨架屏 -->
    <section id="coupons" class="py-8 md:py-12 bg-white">
        <div class="container mx-auto px-4 md:px-6">
            <h2 class="text-[clamp(1.2rem,2vw,1.8rem)] font-bold text-neutral-600 mb-6 flex items-center">
                <i class="fa fa-ticket text-secondary mr-2"></i>优惠券中心
            </h2>

            <!-- 优惠券容器（动态填充） -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 md:gap-6" id="couponContainer">
                <!-- 加载中骨架屏 -->
                <div class="h-40 skeleton rounded-xl"></div>
                <div class="h-40 skeleton rounded-xl"></div>
                <div class="h-40 skeleton rounded-xl"></div>
            </div>

            <!-- 领取成功提示（默认隐藏） -->
            <div id="couponSuccess" class="fixed top-1/3 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-xl shadow-xl p-6 z-50 opacity-0 invisible transition-all duration-300 max-w-md w-4/5">
                <div class="text-center">
                    <div class="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-check text-green-500 text-2xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-neutral-800 mb-2">领取成功！</h3>
                    <p class="text-neutral-500 mb-4" id="couponName">优惠券已放入您的账户</p>
                    <button id="closeCouponSuccess" class="bg-primary text-white font-medium py-2 px-6 rounded-full hover:bg-primary/90 transition-custom">
                        确认
                    </button>
                </div>
            </div>
        </div>
    </section>

    <!-- 精选推荐 - 初始加载骨架屏 -->
    <section class="py-8 md:py-12 bg-neutral-50">
        <div class="container mx-auto px-4 md:px-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-[clamp(1.2rem,2vw,1.8rem)] font-bold text-neutral-600 flex items-center">
                    <i class="fa fa-star text-secondary mr-2"></i>精选推荐
                </h2>
                <a href="#" class="text-primary hover:text-primary/80 font-medium flex items-center transition-custom">
                    查看全部 <i class="fa fa-angle-right ml-1"></i>
                </a>
            </div>

            <!-- 精选商品容器（动态填充） -->
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6" id="featuredProductContainer">
                <!-- 加载中骨架屏（4个） -->
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-48 skeleton"></div>
                    <div class="p-4 space-y-3">
                        <div class="h-4 skeleton rounded w-1/3"></div>
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-48 skeleton"></div>
                    <div class="p-4 space-y-3">
                        <div class="h-4 skeleton rounded w-1/3"></div>
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-48 skeleton"></div>
                    <div class="p-4 space-y-3">
                        <div class="h-4 skeleton rounded w-1/3"></div>
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-48 skeleton"></div>
                    <div class="p-4 space-y-3">
                        <div class="h-4 skeleton rounded w-1/3"></div>
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 新品上架 - 初始加载骨架屏 -->
    <section class="py-8 md:py-12 bg-white">
        <div class="container mx-auto px-4 md:px-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-[clamp(1.2rem,2vw,1.8rem)] font-bold text-neutral-600 flex items-center">
                    <i class="fa fa-clock-o text-primary mr-2"></i>新品上架
                </h2>
                <a href="#" class="text-primary hover:text-primary/80 font-medium flex items-center transition-custom">
                    查看全部 <i class="fa fa-angle-right ml-1"></i>
                </a>
            </div>

            <!-- 新品容器（动态填充） -->
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 md:gap-6" id="newProductContainer">
                <!-- 加载中骨架屏（5个） -->
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-40 skeleton"></div>
                    <div class="p-3 space-y-2">
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-40 skeleton"></div>
                    <div class="p-3 space-y-2">
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-40 skeleton"></div>
                    <div class="p-3 space-y-2">
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-40 skeleton"></div>
                    <div class="p-3 space-y-2">
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
                <div class="bg-white rounded-xl overflow-hidden shadow-card">
                    <div class="h-40 skeleton"></div>
                    <div class="p-3 space-y-2">
                        <div class="h-4 skeleton rounded w-full"></div>
                        <div class="h-4 skeleton rounded w-2/3"></div>
                        <div class="h-6 skeleton rounded w-1/4"></div>
                        <div class="h-10 skeleton rounded w-full"></div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<!-- 优惠券选择弹窗（新增） -->
<div class="coupon-modal fixed inset-0 bg-black/50 z-50 flex items-center justify-center opacity-0 invisible" id="couponModal">
    <div class="coupon-modal-content bg-white rounded-2xl shadow-modal w-full max-w-md mx-4 opacity-0">
        <!-- 弹窗头部 -->
        <div class="flex justify-between items-center p-5 border-b border-neutral-200">
            <h3 class="text-xl font-bold text-neutral-800">选择优惠券</h3>
            <button class="text-neutral-400 hover:text-neutral-600 transition-custom" id="closeCouponModal">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>

        <!-- 商品信息 -->
        <div class="p-5 border-b border-neutral-200" id="modalProductInfo">
            <div class="flex items-start space-x-4">
                <img src="" alt="商品图片" class="w-20 h-20 rounded-lg object-cover" id="modalProductImg">
                <div class="flex-1">
                    <h4 class="font-medium text-neutral-800 line-clamp-2" id="modalProductName"></h4>
                    <div class="mt-2 flex items-baseline">
                        <span class="text-2xl font-bold text-primary" id="modalProductPrice"></span>
                        <span class="text-neutral-400 text-sm line-through ml-2" id="modalProductOriginalPrice"></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 优惠券列表 -->
        <div class="p-5 max-h-80 overflow-y-auto scrollbar-hide" id="modalCouponList">
            <!-- 加载提示 -->
            <div class="text-center py-8" id="couponLoading">
                <div class="w-10 h-10 border-4 border-primary/30 border-t-primary rounded-full animate-spin mx-auto mb-3"></div>
                <p class="text-neutral-500">正在获取可用优惠券...</p>
            </div>

            <!-- 无优惠券提示（默认隐藏） -->
            <div class="empty-tip hidden" id="noCouponTip">
                <i class="fa fa-ticket mr-2"></i> 暂无可用优惠券
            </div>

            <!-- 优惠券列表容器（动态填充） -->
            <div class="space-y-3 hidden" id="couponOptionsContainer">
                <!-- 无优惠券选项（默认选中） -->
                <div class="coupon-option coupon-selected p-4 rounded-xl border border-neutral-200 flex justify-between items-center cursor-pointer"
                     data-coupon-id="0" data-coupon-amount="0">
                    <div class="flex items-center">
                        <div class="w-5 h-5 rounded-full border border-neutral-300 flex items-center justify-center mr-3">
                            <i class="fa fa-check text-primary coupon-check text-sm"></i>
                        </div>
                        <div>
                            <div class="font-medium text-neutral-800">不使用优惠券</div>
                            <div class="text-sm text-neutral-400">原价支付，无优惠</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 价格汇总 -->
        <div class="p-5 border-t border-neutral-200">
            <div class="flex justify-between items-center mb-4">
                <span class="text-neutral-600">商品原价</span>
                <span class="text-neutral-800" id="summaryOriginalPrice"></span>
            </div>
            <div class="flex justify-between items-center mb-4">
                <span class="text-neutral-600">优惠金额</span>
                <span class="text-red-500 font-medium" id="summaryDiscountAmount">¥0.00</span>
            </div>
            <div class="flex justify-between items-center font-bold text-lg">
                <span class="text-neutral-800">实付款</span>
                <span class="text-primary text-xl" id="summaryFinalPrice"></span>
            </div>

            <!-- 付款按钮 -->
            <button class="w-full mt-5 bg-primary text-white font-medium py-3 px-4 rounded-xl hover:bg-primary/90 transition-custom flex items-center justify-center gap-2"
                    id="payButton">
                <i class="fa fa-credit-card"></i>
                <span>确认付款</span>
            </button>
        </div>
    </div>
</div>

<!-- 支付成功弹窗（新增） -->
<div class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-xl shadow-xl p-6 z-50 opacity-0 invisible transition-all duration-300 max-w-md w-4/5" id="paySuccessModal">
    <div class="text-center">
        <div class="w-20 h-20 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
            <i class="fa fa-check-circle text-green-500 text-3xl"></i>
        </div>
        <h3 class="text-xl font-bold text-neutral-800 mb-2">支付成功！</h3>
        <p class="text-neutral-500 mb-6" id="paySuccessMsg">您已成功购买该商品，订单将尽快为您发货</p>
        <div class="flex space-x-3">
            <a href="#" class="flex-1 bg-neutral-100 text-neutral-600 font-medium py-2 px-4 rounded-lg hover:bg-neutral-200 transition-custom">
                查看订单
            </a>
            <button class="flex-1 bg-primary text-white font-medium py-2 px-4 rounded-lg hover:bg-primary/90 transition-custom" id="closePaySuccess">
                返回首页
            </button>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script>
    // ========================= 1. 核心工具函数（防止数据异常） =========================
    /**
     * 安全处理数组数据：确保返回数组（非数组则转为空数组）
     * @param {any} data - 原始数据
     * @returns {Array} 安全数组
     */
    function safeArray(data) {
        return Array.isArray(data) ? data : [];
    }

    /**
     * 安全获取属性值：防止属性不存在导致报错
     * @param {Object} obj - 目标对象
     * @param {string} key - 属性名
     * @param {any} defaultValue - 默认值
     * @returns {any} 属性值或默认值
     */
    function safeGet(obj, key, defaultValue = '') {
        if (typeof obj !== 'object' || obj === null) return defaultValue;
        return obj[key] ?? defaultValue;
    }

    /**
     * 格式化价格：保留两位小数，添加¥符号
     * @param {number} price - 价格
     * @returns {string} 格式化后的价格字符串
     */
    function formatPrice(price) {
        return `¥${Number(price).toFixed(2)}`;
    }

    // ========================= 2. 后端接口请求函数 =========================
    /**
     * 从后端获取精选推荐商品数据
     * @param {number} pageNum - 页码（默认1）
     * @param {number} pageSize - 每页条数（默认4，与后端默认一致）
     * @returns {Promise<Array>} 精选商品数组
     */
    async function getFeaturedProductsFromBackend(pageNum = 1, pageSize = 4) {
        try {
            const response = await fetch(`http://localhost:8080/api/products/featured?pageNum=${pageNum}&pageSize=${pageSize}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`接口请求失败，状态码: ${response.status}`);
            }

            const result = await response.json();
            if (safeGet(result, 'code') !== 200) {
                throw new Error(safeGet(result, 'msg', '精选商品数据获取失败'));
            }

            return safeArray(safeGet(result, 'data', {}).records);
        } catch (error) {
            console.error('精选商品接口请求失败:', error.message);
            throw error;
        }
    }

    /**
     * 从后端获取新品上架商品数据
     * @param {number} pageNum - 页码（默认1）
     * @param {number} pageSize - 每页条数（默认5，与后端默认一致）
     * @returns {Promise<Array>} 新品商品数组
     */
    async function getNewProductsFromBackend(pageNum = 1, pageSize = 5) {
        try {
            const response = await fetch(`http://localhost:8080/api/products/new?pageNum=${pageNum}&pageSize=${pageSize}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`接口请求失败，状态码: ${response.status}`);
            }

            const result = await response.json();
            if (safeGet(result, 'code') !== 200) {
                throw new Error(safeGet(result, 'msg', '新品上架数据获取失败'));
            }

            return safeArray(safeGet(result, 'data', {}).records);
        } catch (error) {
            console.error('新品上架接口请求失败:', error.message);
            throw error;
        }
    }

    /**
     * 从后端获取当前用户的可用优惠券（核心新增）
     * @param {number} productId - 商品ID（用于判断优惠券适用性）
     * @param {number} productPrice - 商品价格（用于判断满减条件）
     * @returns {Promise<Array>} 可用优惠券数组
     */
    async function getUserCouponsFromBackend(productId, productPrice) {
        try {
            // 实际项目中需要传递用户token（此处模拟已登录状态）
            const token = localStorage.getItem('userToken') || 'mock_token';

            const response = await fetch(`http://localhost:8080/api/coupons/user/available`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}` // 用户身份认证
                },
                body: JSON.stringify({
                    productId: productId,
                    productPrice: productPrice
                })
            });
            if (!response.ok) {
                throw new Error(`优惠券接口请求失败，状态码: ${response.status}`);
            }

            const result = await response.json();
            if (safeGet(result, 'code') !== 200) {
                throw new Error(safeGet(result, 'msg', '优惠券数据获取失败'));
            }

            return safeArray(safeGet(result, 'data', []));
        } catch (error) {
            console.error('用户优惠券接口请求失败:', error.message);
            throw error;
        }
    }

    /**
     * 提交订单并支付（核心新增）
     * @param {number} productId - 商品ID
     * @param {number} couponId - 选中的优惠券ID（0表示不使用）
     * @param {number} finalPrice - 实付金额
     * @returns {Promise<boolean>} 支付是否成功
     */
    async function submitOrderAndPay(productId, couponId, finalPrice) {
        try {
            const token = localStorage.getItem('userToken') || 'mock_token';

            const response = await fetch(`http://localhost:8080/api/orders/createAndPay`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    productId: productId,
                    couponId: couponId,
                    payAmount: finalPrice,
                    payType: 'ONLINE' // 在线支付
                })
            });

            if (!response.ok) {
                throw new Error(`支付接口请求失败，状态码: ${response.status}`);
            }

            const result = await response.json();
            if (safeGet(result, 'code') !== 200) {
                throw new Error(safeGet(result, 'msg', '支付失败'));
            }

            return true;
        } catch (error) {
            console.error('支付请求失败:', error.message);
            throw error;
        }
    }

    // ========================= 3. Mock数据（轮播图/优惠券） =========================
    const mockApi = {
        getCarouselData: () => {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve([
                        {
                            id: 1,
                            imgUrl: "https://picsum.photos/id/1068/1600/500",
                            title: "夏季好物特惠",
                            desc: "精选二手好物低至3折，品质保证",
                            btnText: "领取优惠券",
                            btnLink: "#coupons"
                        },
                        {
                            id: 2,
                            imgUrl: "https://picsum.photos/id/1048/1600/500",
                            title: "数码产品专场",
                            desc: "9成新数码产品，官方质检认证",
                            btnText: "查看专区",
                            btnLink: "#"
                        }
                    ]);
                }, 800);
            });
        },

        getCouponData: () => {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve([
                        {
                            id: 1,
                            type: "新用户专享",
                            amount: 10,
                            condition: "无门槛券",
                            fullPrice: 0,
                            validDate: "2025-12-31",
                            bgFrom: "from-primary/90",
                            bgTo: "to-primary",
                            textColor: "text-white",
                            btnTextColor: "text-primary"
                        },
                        {
                            id: 2,
                            type: "",
                            amount: 30,
                            condition: "满减券",
                            fullPrice: 300,
                            validDate: "2025-12-15",
                            bgFrom: "from-secondary/90",
                            bgTo: "to-secondary",
                            textColor: "text-white",
                            btnTextColor: "text-secondary"
                        },
                        {
                            id: 3,
                            type: "",
                            amount: 50,
                            condition: "满减券",
                            fullPrice: 500,
                            validDate: "2025-12-10",
                            bgFrom: "from-purple-600/90",
                            bgTo: "to-purple-500",
                            textColor: "text-white",
                            btnTextColor: "text-purple-600"
                        }
                    ]);
                }, 1000);
            });
        }
    };

    // ========================= 4. 渲染函数 =========================
    /**
     * 渲染轮播图
     * @param {any} rawData - 原始轮播数据
     */
    function renderCarousel(rawData) {
        const container = document.getElementById('carouselContainer');
        const indicators = document.getElementById('carouselIndicators');
        const data = safeArray(rawData);

        container.innerHTML = '';
        indicators.innerHTML = '';

        if (data.length === 0) {
            container.innerHTML = `
                <div class="carousel-item min-w-full h-full empty-tip">
                    <i class="fa fa-picture-o mr-2"></i> 暂无轮播图数据
                </div>
            `;
            return;
        }

        data.forEach((item, index) => {
            const imgUrl = safeGet(item, 'imgUrl', 'https://picsum.photos/1600/500');
            const title = safeGet(item, 'title', '活动标题');
            const desc = safeGet(item, 'desc', '暂无活动描述');
            const btnText = safeGet(item, 'btnText', '查看详情');
            const btnLink = safeGet(item, 'btnLink', '#');

            const carouselItem = document.createElement('div');
            carouselItem.className = `carousel-item min-w-full h-full ${index === 0 ? 'active' : ''}`;
            carouselItem.innerHTML = `
                <img src="${imgUrl}" alt="${title}" class="w-full h-full object-cover">
                <div class="absolute inset-0 bg-gradient-to-r from-black/60 to-transparent flex items-center">
                    <div class="px-6 md:px-12 max-w-md">
                        <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-white mb-3 text-shadow">${title}</h2>
                        <p class="text-white/90 mb-6 text-[clamp(1rem,1.5vw,1.2rem)]">${desc}</p>
                        <a href="${btnLink}" class="inline-block bg-secondary hover:bg-secondary/90 text-white font-medium py-3 px-8 rounded-full transition-custom">
                            ${btnText}
                        </a>
                    </div>
                </div>
            `;
            container.appendChild(carouselItem);

            const indicatorBtn = document.createElement('button');
            indicatorBtn.className = `w-3 h-3 rounded-full bg-white/50 hover:bg-white transition-custom carousel-indicator ${index === 0 ? 'bg-white' : ''}`;
            indicatorBtn.setAttribute('data-index', index);
            indicators.appendChild(indicatorBtn);
        });
    }

    /**
     * 渲染优惠券
     * @param {any} rawData - 原始优惠券数据
     */
    function renderCoupons(rawData) {
        const container = document.getElementById('couponContainer');
        const data = safeArray(rawData);

        container.innerHTML = '';

        if (data.length === 0) {
            container.innerHTML = `
                <div class="col-span-full empty-tip">
                    <i class="fa fa-ticket mr-2"></i> 暂无优惠券数据
                </div>
            `;
            return;
        }

        data.forEach(coupon => {
            const type = safeGet(coupon, 'type');
            const amount = safeGet(coupon, 'amount', 0);
            const condition = safeGet(coupon, 'condition', '优惠券');
            const fullPrice = safeGet(coupon, 'fullPrice', 0);
            const validDate = safeGet(coupon, 'validDate', '2025-12-31');
            const bgFrom = safeGet(coupon, 'bgFrom', 'from-gray-500/90');
            const bgTo = safeGet(coupon, 'bgTo', 'to-gray-500');
            const textColor = safeGet(coupon, 'textColor', 'text-white');
            const btnTextColor = safeGet(coupon, 'btnTextColor', 'text-gray-600');

            const tagHtml = type
                ? `<div class="absolute top-0 right-0 w-20 h-20">
                    <div class="absolute transform rotate-45 bg-secondary text-white text-xs font-bold py-1 right-[-35px] top-[15px] w-[140px] text-center">
                        ${type}
                    </div>
                  </div>`
                : '';

            const couponCard = document.createElement('div');
            couponCard.className = `coupon-card bg-gradient-to-r ${bgFrom} ${bgTo} rounded-xl overflow-hidden shadow-card coupon-hover relative`;
            couponCard.innerHTML = `
                ${tagHtml}
                <div class="p-6 ${textColor} flex flex-col md:flex-row items-center justify-between">
                    <div class="text-center md:text-left mb-4 md:mb-0">
                        <div class="flex items-baseline justify-center md:justify-start">
                            <span class="text-4xl md:text-5xl font-bold">¥${amount}</span>
                            <span class="ml-2">${condition}</span>
                        </div>
                        <p class="${textColor}/80 mt-2 text-sm">满${fullPrice}元即可使用</p>
                        <p class="${textColor}/80 mt-1 text-sm">有效期至 ${validDate}</p>
                    </div>
                    <button class="coupon-btn bg-white ${btnTextColor} font-bold py-2 px-6 rounded-full hover:bg-neutral-100 transition-custom"
                            data-coupon="¥${amount}${condition}">
                        立即领取
                    </button>
                </div>
            `;
            container.appendChild(couponCard);
        });
    }

    /**
     * 生成星级评分HTML
     * @param {any} rating - 原始评分（默认0）
     * @returns {string} 星级HTML
     */
    function generateStarRating(rating) {
        const safeRating = Math.max(0, Math.min(5, Number(rating) || 0));
        const fullStars = Math.floor(safeRating);
        const hasHalfStar = safeRating % 1 >= 0.5;
        const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);

        let starHtml = '';
        for (let i = 0; i < fullStars; i++) starHtml += '<i class="fa fa-star"></i>';
        if (hasHalfStar) starHtml += '<i class="fa fa-star-half-o"></i>';
        for (let i = 0; i < emptyStars; i++) starHtml += '<i class="fa fa-star-o"></i>';

        return starHtml;
    }

    /**
     * 渲染精选推荐商品
     * @param {any} rawData - 原始商品数据
     */
    function renderFeaturedProducts(rawData) {
        const container = document.getElementById('featuredProductContainer');
        const data = safeArray(rawData);

        container.innerHTML = '';

        if (data.length === 0) {
            container.innerHTML = `
                <div class="col-span-full empty-tip">
                    <i class="fa fa-shopping-bag mr-2"></i> 暂无精选商品数据
                </div>
            `;
            return;
        }

        data.forEach(product => {
            const id = safeGet(product, 'id', '');
            const imgUrl = safeGet(product, 'imgUrl', 'https://picsum.photos/400/300');
            const quality = safeGet(product, 'quality', '未知成色');
            const delivery = safeGet(product, 'delivery', '配送方式未知');
            const title = safeGet(product, 'title', '商品名称');
            const rating = safeGet(product, 'rating', 0);
            const reviewCount = safeGet(product, 'reviewCount', 0);
            const price = safeGet(product, 'price', 0);
            const originalPrice = safeGet(product, 'originalPrice', 0);

            const productCard = document.createElement('div');
            productCard.className = 'product-card bg-white rounded-xl overflow-hidden shadow-card hover:shadow-card-hover transition-custom';
            productCard.innerHTML = `
                <div class="relative">
                    <img src="${imgUrl}" alt="${title}" class="w-full h-48 object-cover">
                    <span class="absolute top-2 left-2 bg-secondary text-white text-xs font-medium py-1 px-2 rounded">${quality}</span>
                    <button class="absolute top-2 right-2 bg-white/80 hover:bg-white text-neutral-500 hover:text-primary w-8 h-8 rounded-full flex items-center justify-center transition-custom">
                        <i class="fa fa-heart-o"></i>
                    </button>
                </div>
                <div class="p-4">
                    <div class="flex items-center text-xs text-neutral-400 mb-2">
                        <span>${delivery}</span>
                    </div>
                    <h3 class="font-medium text-neutral-600 mb-2 line-clamp-2">${title}</h3>
                    <div class="flex items-center mb-3">
                        <div class="flex text-yellow-400 text-xs">
                            ${generateStarRating(rating)}
                        </div>
                        <span class="text-neutral-400 text-xs ml-1">(${reviewCount})</span>
                    </div>
                    <div class="flex justify-between items-center mb-3">
                        <span class="font-bold text-xl text-neutral-800">¥${price}</span>
                        <span class="text-neutral-400 text-sm line-through">¥${originalPrice}</span>
                    </div>
                    <!-- 购买按钮 -->
                    <button class="buy-btn w-full bg-primary text-white font-medium py-2 px-4 rounded-lg hover:bg-primary/90 flex items-center justify-center gap-2"
                            data-product-id="${id}"
                            data-product-name="${title}"
                            data-product-price="${price}"
                            data-product-original-price="${originalPrice}"
                            data-product-img="${imgUrl}"
                            onclick="handleBuyClick(this)">
                        <i class="fa fa-shopping-cart"></i>
                        <span>立即购买</span>
                    </button>
                </div>
            `;
            container.appendChild(productCard);
        });
    }

    /**
     * 渲染新品上架商品
     * @param {any} rawData - 原始商品数据
     */
    function renderNewProducts(rawData) {
        const container = document.getElementById('newProductContainer');
        const data = safeArray(rawData);

        container.innerHTML = '';

        if (data.length === 0) {
            container.innerHTML = `
                <div class="col-span-full empty-tip">
                    <i class="fa fa-clock-o mr-2"></i> 暂无新品上架数据
                </div>
            `;
            return;
        }

        data.forEach(product => {
            const id = safeGet(product, 'id', '');
            const imgUrl = safeGet(product, 'imgUrl', 'https://picsum.photos/400/300');
            const title = safeGet(product, 'title', '商品名称');
            const rating = safeGet(product, 'rating', 0);
            const reviewCount = safeGet(product, 'reviewCount', 0);
            const price = safeGet(product, 'price', 0);
            const originalPrice = safeGet(product, 'originalPrice', 0);

            const productCard = document.createElement('div');
            productCard.className = 'product-card bg-white rounded-xl overflow-hidden shadow-card hover:shadow-card-hover transition-custom';
            productCard.innerHTML = `
                <div class="relative">
                    <img src="${imgUrl}" alt="${title}" class="w-full h-40 object-cover">
                    <span class="absolute top-2 left-2 bg-primary text-white text-xs font-medium py-1 px-2 rounded">新品</span>
                    <button class="absolute top-2 right-2 bg-white/80 hover:bg-white text-neutral-500 hover:text-primary w-8 h-8 rounded-full flex items-center justify-center transition-custom">
                        <i class="fa fa-heart-o"></i>
                    </button>
                </div>
                <div class="p-3">
                    <h3 class="font-medium text-neutral-600 mb-1 line-clamp-2 text-sm">${title}</h3>
                    <div class="flex items-center mb-2">
                        <div class="flex text-yellow-400 text-[10px]">
                            ${generateStarRating(rating)}
                        </div>
                        <span class="text-neutral-400 text-[10px] ml-1">(${reviewCount})</span>
                    </div>
                    <div class="flex justify-between items-center mb-3">
                        <span class="font-bold text-lg text-neutral-800">¥${price}</span>
                        <span class="text-neutral-400 text-xs line-through">¥${originalPrice}</span>
                    </div>
                    <!-- 购买按钮 -->
                    <button class="buy-btn w-full bg-primary text-white font-medium py-2 px-4 rounded-lg hover:bg-primary/90 flex items-center justify-center gap-2"
                            data-product-id="${id}"
                            data-product-name="${title}"
                            data-product-price="${price}"
                            data-product-original-price="${originalPrice}"
                            data-product-img="${imgUrl}"
                            onclick="handleBuyClick(this)">
                        <i class="fa fa-shopping-cart"></i>
                        <span>立即购买</span>
                    </button>
                </div>
            `;
            container.appendChild(productCard);
        });
    }

    /**
     * 渲染用户可用优惠券到弹窗
     * @param {Array} coupons - 优惠券数组
     * @param {number} productPrice - 商品价格
     */
    function renderUserCoupons(coupons, productPrice) {
        const container = document.getElementById('couponOptionsContainer');
        const noCouponTip = document.getElementById('noCouponTip');
        const loading = document.getElementById('couponLoading');

        // 隐藏加载提示
        loading.classList.add('hidden');

        // 清除现有优惠券（保留"不使用优惠券"选项）
        const defaultOption = container.querySelector('[data-coupon-id="0"]');
        container.innerHTML = '';
        container.appendChild(defaultOption);

        // 无可用优惠券
        if (coupons.length === 0) {
            noCouponTip.classList.remove('hidden');
            container.classList.add('hidden');
            return;
        }

        // 显示优惠券列表
        noCouponTip.classList.add('hidden');
        container.classList.remove('hidden');

        // 渲染可用优惠券
        coupons.forEach(coupon => {
            const id = safeGet(coupon, 'id', 0);
            const amount = safeGet(coupon, 'amount', 0);
            const condition = safeGet(coupon, 'condition', '优惠券');
            const fullPrice = safeGet(coupon, 'fullPrice', 0);
            const validDate = safeGet(coupon, 'validDate', '');
            const type = safeGet(coupon, 'type', '');

            // 判断优惠券是否可用（满减条件）
            const isAvailable = fullPrice <= productPrice;

            const couponOption = document.createElement('div');
            couponOption.className = `coupon-option p-4 rounded-xl border border-neutral-200 flex justify-between items-center cursor-pointer ${isAvailable ? '' : 'coupon-disabled'}`;
            couponOption.setAttribute('data-coupon-id', id);
            couponOption.setAttribute('data-coupon-amount', amount);
            couponOption.innerHTML = `
                <div class="flex items-center">
                    <div class="w-5 h-5 rounded-full border border-neutral-300 flex items-center justify-center mr-3">
                        <i class="fa fa-check text-primary coupon-check text-sm"></i>
                    </div>
                    <div>
                        <div class="font-medium text-neutral-800 flex items-center">
                            ¥${amount} ${condition}
                            ${type ? `<span class="ml-2 bg-primary/10 text-primary text-xs py-0.5 px-2 rounded">${type}</span>` : ''}
                        </div>
                        <div class="text-sm text-neutral-400">
                            ${fullPrice > 0 ? `满¥${fullPrice}可用 | ` : ''}有效期至 ${validDate}
                            ${!isAvailable ? `<span class="text-red-500 ml-2">（未满使用条件）</span>` : ''}
                        </div>
                    </div>
                </div>
                <div class="text-primary font-medium">-¥${amount.toFixed(2)}</div>
            `;

            // 不可用优惠券添加禁用事件
            if (!isAvailable) {
                couponOption.style.pointerEvents = 'none';
            } else {
                couponOption.addEventListener('click', () => selectCoupon(couponOption));
            }

            container.appendChild(couponOption);
        });
    }

    // ========================= 5. 核心交互逻辑 =========================
    /**
     * 购买按钮点击事件（核心修改）
     * @param {HTMLElement} btn - 购买按钮元素
     */
    async function handleBuyClick(btn) {
        // 获取商品信息
        const productId = btn.getAttribute('data-product-id');
        const productName = btn.getAttribute('data-product-name');
        const productPrice = Number(btn.getAttribute('data-product-price')) || 0;
        const productOriginalPrice = Number(btn.getAttribute('data-product-original-price')) || 0;
        const productImg = btn.getAttribute('data-product-img') || 'https://picsum.photos/400/300';

        // 存储当前商品信息到全局（用于支付时使用）
        window.currentOrderInfo = {
            productId,
            productName,
            productPrice,
            productOriginalPrice,
            selectedCouponId: 0,
            selectedCouponAmount: 0
        };

        // 填充弹窗商品信息
        document.getElementById('modalProductName').textContent = productName;
        document.getElementById('modalProductPrice').textContent = formatPrice(productPrice);
        document.getElementById('modalProductOriginalPrice').textContent = formatPrice(productOriginalPrice);
        document.getElementById('modalProductImg').src = productImg;
        document.getElementById('modalProductImg').alt = productName;

        // 填充价格汇总
        document.getElementById('summaryOriginalPrice').textContent = formatPrice(productPrice);
        document.getElementById('summaryFinalPrice').textContent = formatPrice(productPrice);

        // 显示弹窗
        const modal = document.getElementById('couponModal');
        modal.classList.add('active');

        try {
            // 调用接口获取用户可用优惠券
            const coupons = await getUserCouponsFromBackend(productId, productPrice);
            renderUserCoupons(coupons, productPrice);
        } catch (error) {
            // 接口请求失败处理
            const loading = document.getElementById('couponLoading');
            const noCouponTip = document.getElementById('noCouponTip');

            loading.classList.add('hidden');
            noCouponTip.classList.remove('hidden');
            noCouponTip.innerHTML = `<i class="fa fa-exclamation-circle mr-2"></i> 优惠券获取失败：${error.message}`;
        }
    }

    /**
     * 选择优惠券
     * @param {HTMLElement} couponElement - 优惠券元素
     */
    function selectCoupon(couponElement) {
        // 移除所有选中状态
        document.querySelectorAll('.coupon-option').forEach(option => {
            option.classList.remove('coupon-selected');
        });

        // 添加当前选中状态
        couponElement.classList.add('coupon-selected');

        // 获取选中的优惠券信息
        const couponId = couponElement.getAttribute('data-coupon-id');
        const couponAmount = Number(couponElement.getAttribute('data-coupon-amount')) || 0;

        // 更新全局订单信息
        window.currentOrderInfo.selectedCouponId = couponId;
        window.currentOrderInfo.selectedCouponAmount = couponAmount;

        // 计算优惠后价格
        const productPrice = window.currentOrderInfo.productPrice;
        const finalPrice = Math.max(0, productPrice - couponAmount);

        // 更新价格显示
        document.getElementById('summaryDiscountAmount').textContent = formatPrice(couponAmount);
        document.getElementById('summaryFinalPrice').textContent = formatPrice(finalPrice);
    }

    /**
     * 付款按钮点击事件
     */
    async function handlePayClick() {
        const payButton = document.getElementById('payButton');
        const originalText = payButton.innerHTML;

        // 防止重复点击
        payButton.disabled = true;
        payButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 支付中...';

        try {
            const { productId, selectedCouponId, productPrice, selectedCouponAmount } = window.currentOrderInfo;
            const finalPrice = Math.max(0, productPrice - selectedCouponAmount);

            // 调用支付接口
            const paySuccess = await submitOrderAndPay(productId, selectedCouponId, finalPrice);

            if (paySuccess) {
                // 关闭优惠券弹窗
                document.getElementById('couponModal').classList.remove('active');

                // 显示支付成功弹窗
                const successModal = document.getElementById('paySuccessModal');
                successModal.classList.remove('opacity-0', 'invisible');
                successModal.classList.add('opacity-100', 'visible', 'animate-fade-in');
            }
        } catch (error) {
            alert(`支付失败：${error.message}`);
        } finally {
            // 恢复按钮状态
            payButton.disabled = false;
            payButton.innerHTML = originalText;
        }
    }

    // ========================= 6. 页面交互初始化 =========================
    function initInteractions() {
        // 1. 导航栏滚动效果
        const navbar = document.getElementById('navbar');
        if (navbar) {
            window.addEventListener('scroll', () => {
                if (window.scrollY > 50) {
                    navbar.classList.add('shadow-md');
                    navbar.classList.remove('shadow-sm');
                } else {
                    navbar.classList.remove('shadow-md');
                    navbar.classList.add('shadow-sm');
                }
            });
        }

        // 2. 移动端菜单切换
        const menuToggle = document.getElementById('menuToggle');
        const mobileMenu = document.getElementById('mobileMenu');
        if (menuToggle && mobileMenu) {
            menuToggle.addEventListener('click', () => {
                mobileMenu.classList.toggle('hidden');
            });
        }

        // 3. 轮播图交互
        const initCarousel = () => {
            const container = document.getElementById('carouselContainer');
            const prevBtn = document.getElementById('prevSlide');
            const nextBtn = document.getElementById('nextSlide');
            const indicators = document.querySelectorAll('.carousel-indicator');
            if (!container || !prevBtn || !nextBtn) return;

            let currentSlide = 0;
            const totalSlides = document.querySelectorAll('.carousel-item').length;

            const goToSlide = (index) => {
                if (totalSlides === 0) return;
                currentSlide = Math.max(0, Math.min(index, totalSlides - 1));
                container.style.transform = `translateX(-${currentSlide * 100}%)`;

                indicators.forEach((btn, i) => {
                    if (i === currentSlide) {
                        btn.classList.add('bg-white');
                        btn.classList.remove('bg-white/50');
                    } else {
                        btn.classList.remove('bg-white');
                        btn.classList.add('bg-white/50');
                    }
                });
            };

            prevBtn.addEventListener('click', () => goToSlide(currentSlide - 1));
            nextBtn.addEventListener('click', () => goToSlide(currentSlide + 1));
            indicators.forEach((btn, index) => {
                btn.addEventListener('click', () => goToSlide(index));
            });

            if (totalSlides > 0) {
                let carouselInterval = setInterval(() => goToSlide(currentSlide + 1), 5000);
                const carousel = document.getElementById('carousel');
                if (carousel) {
                    carousel.addEventListener('mouseenter', () => clearInterval(carouselInterval));
                    carousel.addEventListener('mouseleave', () => {
                        carouselInterval = setInterval(() => goToSlide(currentSlide + 1), 5000);
                    });
                }
            }
        };

        // 4. 优惠券领取功能
        const initCoupon = () => {
            const successModal = document.getElementById('couponSuccess');
            const couponName = document.getElementById('couponName');
            const closeBtn = document.getElementById('closeCouponSuccess');
            if (!successModal || !couponName || !closeBtn) return;

            document.addEventListener('click', (e) => {
                const btn = e.target.closest('.coupon-btn');
                if (btn && !btn.disabled) {
                    const coupon = btn.getAttribute('data-coupon') || '优惠券';
                    couponName.textContent = `${coupon}已放入您的账户`;

                    successModal.classList.remove('opacity-0', 'invisible');
                    successModal.classList.add('opacity-100', 'visible', 'animate-fade-in');

                    btn.textContent = '已领取';
                    btn.classList.add('bg-neutral-300', 'text-neutral-500');
                    btn.classList.remove('hover:bg-neutral-100');
                    btn.disabled = true;
                }
            });

            closeBtn.addEventListener('click', () => {
                successModal.classList.add('opacity-0', 'invisible');
            });

            successModal.addEventListener('click', (e) => {
                if (e.target === successModal) {
                    successModal.classList.add('opacity-0', 'invisible');
                }
            });
        };

        // 5. 商品卡片悬停效果
        const initProductHover = () => {
            document.addEventListener('mouseenter', (e) => {
                const card = e.target.closest('.product-card');
                if (card) {
                    const heartBtn = card.querySelector('button:has(.fa-heart-o)');
                    if (heartBtn) heartBtn.classList.add('animate-pulse');
                }
            });

            document.addEventListener('mouseleave', (e) => {
                const card = e.target.closest('.product-card');
                if (card) {
                    const heartBtn = card.querySelector('button:has(.fa-heart-o)');
                    if (heartBtn) heartBtn.classList.remove('animate-pulse');
                }
            });
        };

        // 6. 优惠券弹窗交互（新增）
        const initCouponModal = () => {
            const modal = document.getElementById('couponModal');
            const closeBtn = document.getElementById('closeCouponModal');
            const payButton = document.getElementById('payButton');

            // 关闭弹窗
            closeBtn.addEventListener('click', () => {
                modal.classList.remove('active');
            });

            // 点击外部关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.classList.remove('active');
                }
            });

            // 付款按钮点击
            payButton.addEventListener('click', handlePayClick);

            // 初始化"不使用优惠券"选项点击事件
            const defaultOption = document.querySelector('[data-coupon-id="0"]');
            if (defaultOption) {
                defaultOption.addEventListener('click', () => selectCoupon(defaultOption));
            }
        };

        // 7. 支付成功弹窗交互（新增）
        const initPaySuccessModal = () => {
            const modal = document.getElementById('paySuccessModal');
            const closeBtn = document.getElementById('closePaySuccess');

            closeBtn.addEventListener('click', () => {
                modal.classList.add('opacity-0', 'invisible');
                // 可跳转到首页或订单列表
                // window.location.href = '/';
            });
        };

        // 执行所有交互初始化
        initCarousel();
        initCoupon();
        initProductHover();
        initCouponModal();
        initPaySuccessModal();
    }

    // ========================= 7. 页面加载主逻辑 =========================
    document.addEventListener('DOMContentLoaded', async () => {
        try {
            // 并行调用接口
            const [carouselData, couponData, featuredProducts, newProducts] = await Promise.all([
                mockApi.getCarouselData().then(safeArray),
                mockApi.getCouponData().then(safeArray),
                getFeaturedProductsFromBackend(),
                getNewProductsFromBackend()
            ]);

            // 渲染所有模块
            renderCarousel(carouselData);
            renderCoupons(couponData);
            renderFeaturedProducts(featuredProducts);
            renderNewProducts(newProducts);

        } catch (error) {
            console.error('页面加载失败:', {
                message: error.message,
                stack: error.stack
            });
            alert(`数据加载失败：${error.message}，请刷新页面重试`);
        }

        // 初始化交互功能
        initInteractions();

        // 模拟用户登录（实际项目中从后端获取token）
        localStorage.setItem('userToken', 'mock_user_token_123456');
    });
</script>
</body>
</html>